package Util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import Interface.MCallBack;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Administrator on 2017/11/3.
 */

public class Util {
    public static boolean checknetwork(Context context){
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        //获取所有网络连接的信息
        Network[] networks = connMgr.getAllNetworks();
        //用于存放网络连接信息
        StringBuilder sb = new StringBuilder();
        //通过循环将网络信息逐个取出来
        for (int i=0; i < networks.length; i++){
            //获取ConnectivityManager对象对应的NetworkInfo对象
            NetworkInfo networkInfo = connMgr.getNetworkInfo(networks[i]);
            sb.append(networkInfo.getTypeName() + " connect is " + networkInfo.isConnected());
            if ( networkInfo.isConnected()==false){
                Toast.makeText(context, "网络连接不可用", Toast.LENGTH_LONG).show();
                return false;
            }
        }
//networkInfo.getTypeName() 网络名称 WIFI或者MOBILE
      //  Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
        if (TextUtils.isEmpty(sb)){
            Toast.makeText(context, "网络未连接", Toast.LENGTH_LONG).show();
            return false;
        }
        return true;
    }
    //下载文件
    public static void updatafile(final String url, final String camerapath,final MCallBack mCallBack){
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean sdCardExist = Environment.getExternalStorageState()
                        .equals(Environment.MEDIA_MOUNTED); //判断sd卡是否存在
                if (!sdCardExist){
                    mCallBack.succes("未发现sd卡！");
                    return;
                }
                File filepath=new File(camerapath);
                if (!filepath.getParentFile().exists()){
                    filepath.getParentFile().mkdirs();
                }
                try {

                    //String urlStr=url.substring(0,url.lastIndexOf("/")+1)+URLEncoder.encode(url.substring(url.lastIndexOf("/")+1,url.length()),"GBK");
                    String urlStr=url;
                    URL url = new URL( urlStr);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5 * 1000);
                    conn.setRequestMethod("GET");
//                    conn.setRequestProperty("Connection", "Keep-Alive");
//                    conn.setRequestProperty("Content-Type", "*/*");
//                    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                    // 读取网络流到inStream中
                    InputStream inStream = conn.getInputStream();

                    // 定入二进制到文件
                    if (filepath.exists()){
                        filepath.delete();
                    }
                    // 在文件系统中根据路径创建一个新的空文件
                    filepath.createNewFile();
                    OutputStream outStream = new FileOutputStream(filepath);
                    byte[] buff = new byte[1024];
                    int hasRead;
                    while ((hasRead = inStream.read(buff)) != -1) {

                        outStream.write(buff, 0, hasRead);
                    }
                    outStream.close();
                    inStream.close();
                    mCallBack.succes(filepath.toString());
                    //conn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }
    //压缩文件
    public static void compressMore(Context context, final List<String> pathList, final MCallBack compressImage){
        Toast.makeText(context, "压缩中", Toast.LENGTH_SHORT).show();
        ArrayList<File> files=new ArrayList<>();
        for (String path :
                pathList) {
            files.add(new File(path));
        }
        Luban2.get(context)
                .load(files)                     //传人要压缩的图片集，也可以是单张图片如 .load(new File(path))
                .putGear(Luban2.THIRD_GEAR)      //设定压缩档次，默认三挡
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // AppManager.I().currentActivity().showDialog("加载中...");
                    }
                    @Override
                    public void onSuccess(File file) {
                        //每压缩完成一张就会有回调文件，多文件压缩onSuccess会不停地被调用返回数据，然后在下列代码中回调出去
                        compressImage.succes(file.getPath());
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();    //启动压缩
    }

}
